from django.shortcuts import render,HttpResponse,redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from app01 import models
import json
import ast
import math
from django.http import JsonResponse
from app01.Lora import *
from app01.forms import LoginForm
import time
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework import exceptions
from rest_framework.authentication import BasicAuthentication

def main(request):
    try:
        v=request.session.get('permissions')
        if int(v)>=1:
            device_list=models.Device_list.objects.all()
            return render(request,'main.html',{'device_list':device_list})
        else:
            return HttpResponse("您的权限不够！")
    except Exception:
        return redirect('/login/')

class PageInfo(object):
    def __init__(self, nid, current_page,all_count,per_page,show_page=11):
        try:
            self.current_page=int(current_page)
        except Exception as e:
            self.current_page=1
        self.per_page=per_page
        a,b=divmod(all_count,per_page)
        if b:
            a=a+1
        self.all_pager=a
        self.show_page=show_page
        self.nid=nid
    def start(self):
        return (self.current_page-1)*self.per_page
    def end(self):
        return  self.current_page*self.per_page
    def pager(self):
        page_list=[]
        half=int((self.show_page-1)/2)
        if self.all_pager<self.show_page:
            begin=1
            stop=self.all_pager+1
        else:
            if self.current_page <= half:
                begin = 1
                stop = self.show_page+1
            else:
                if self.current_page+half>self.all_pager:
                    begin=self.all_pager-self.show_page+1
                    stop=self.all_pager+1
                else:
                    begin=self.current_page-half
                    stop=self.current_page+half+1
        if self.current_page<=1:
            prev = "<a class='pagebutton' style='display:inline-block;padding:5px;margin:5px;' href='#' onclick='return false;'>上一页</a>"
        else:
            prev ="<a class='pagebutton' style='display:inline-block;padding:5px;margin:5px;' href='/more_data/?page=%s&nid=%s' onclick='return false;'>上一页</a>"%(self.current_page-1,self.nid,)
        page_list.append(prev)

        for i in range(begin,stop):
            if i==self.current_page:
                temp="<a class='pagebutton' style='display:inline-block;padding:5px;margin:5px;background-color:#2e6da4;color:white' href='/more_data/?page=%s&nid=%s'  onclick='return false;'>%s</a>"%(i,self.nid,i,)
            else:
                temp="<a class='pagebutton' style='display:inline-block;padding:5px;margin:5px;' href='/more_data/?page=%s&nid=%s' onclick='return false;'>%s</a>"%(i,self.nid,i,)
            page_list.append(temp)

        if self.current_page==self.all_pager:
            next="<a class='pagebutton' style='display:inline-block;padding:5px;margin:5px;' href='#' onclick='return false;'>下一页</a>"
        else:
            next = "<a  class='pagebutton' style='display:inline-block;padding:5px;margin:5px;' href='/more_data/?page=%s&nid=%s' onclick='return false;'>下一页</a>" % (self.current_page+1,self.nid,)
        page_list.append(next)
        return ''.join(page_list)

def more_data(request):
    try:
        v = request.session.get('permissions')
        if int(v)>=2:
            nid=request.GET.get('nid')
            all_count = models.Device_data.objects.filter(ug_id=nid).count()
            page_info = PageInfo(nid, request.GET.get('page'), all_count, 20)
            device_data = models.Device_data.objects.filter(ug_id=nid).order_by('-id')[page_info.start():page_info.end()]
            return render(request, 'more_data.html', {'device_data': device_data, 'page_info': page_info})
    except Exception:
        return redirect('/login/')


def modal_add_device(request):
    try:
        v=request.session.get('permissions')
        if int(v)>=3:
            name = request.POST.get('name')
            mac = request.POST.get('mac')
            models.Device_list.objects.create(device_name=name, device_mac=mac)
            return redirect('/main/')
        else:
            return HttpResponse("您的权限不够！")
    except Exception:
        return redirect('/login/')

class Dataget(APIView):
    def get(self,request,*args,**kwargs):
        devicemac=request._request.GET.get('mac')
        uid=models.Device_list.objects.get(device_mac=devicemac)
        last_device_data=models.Satellites.objects.filter(ug_id=uid).last()
        if last_device_data.response:
            log=ast.literal_eval(last_device_data.response)
            if 'latitude' in log:
                latitude=log['latitude']
                longitude=log['longitude']
                height=log['height']
                return JsonResponse({"satellites number": last_device_data.num,
                                     "latitude": latitude,
                                     "longitude":longitude,
                                     "height":height})
            elif 'errorMessage' in log:
                content='Positioning fails!The number of satellites is not enough!'
                return JsonResponse({"satellites number": last_device_data.num, "error message": content})
        else:
            content='Positioning fails!The connection of servers is not established!'
            return JsonResponse({"satellites number": last_device_data.num, "error message": content})


def get_data(request):
    devicemac=request.GET.get('mac')
    uid=models.Device_list.objects.get(device_mac=devicemac)
    last_device_data=models.Device_data.objects.filter(ug_id=uid).last()
    return HttpResponse(last_device_data)

H = HttpClient('https://884v0jtyha.execute-api.cn-north-1.amazonaws.com.cn/default/entry', 'whatever')

initTime={}

def post_data(request):
    global H
    global initTime
    deviceinittime=time.time()
    try:
        resp=request.body.decode()
        devicemac=json.loads(resp)['mac']
        datafromlora=json.loads(resp)['data']
        deviceappeui=json.loads(resp)['appeui']
        flag=datafromlora[0:2]
        pub_payload=datafromlora[4:-2]
        if models.Device_list.objects.filter(device_mac=devicemac).first() and pack('<I',crc32(bytes.fromhex(datafromlora[:-2])))[:1].hex()==datafromlora[-2:]:
            if flag == CMD_PUBLIC_ID_ANS:
                public_id = pub_payload
                models.Device_list.objects.filter(device_mac=devicemac).update(device_pubilicid=public_id)
            elif flag == CMD_POINT_ANS or flag == SRV_CMD_POSITION_RESULT_REQ:
                pr_data = pub_payload
                satellites_num=len(pr_data)//16
                uid = models.Device_list.objects.get(device_mac=devicemac)
                date_year = int(time.strftime("%Y"))
                date_month = int(time.strftime("%m"))
                date_day = int(time.strftime("%d"))
                date_hour = int(time.strftime("%H"))
                date_minute = int(time.strftime("%M"))
                date_second = int(time.strftime("%S"))
                public_id = models.Device_list.objects.get(device_mac=devicemac).device_pubilicid
                if not public_id:
                    header = SerialHeader(int(CMD_PUBLIC_ID_REQ),0)
                    reply = SerialCommand(header, None)
                    LoraServes_post((reply.bytes).hex(), devicemac, deviceappeui)
                    return JsonResponse({"code":0,"msg":"success"})
                pointtime=time.time()
                resp = H.point_entry(
                    bytes.fromhex(public_id), int(10), bytes.fromhex(pr_data),
                    30.47, 114.41, 35
                )
                print("请求时间为:",time.time()-pointtime)
                if resp:
                    models.Satellites.objects.create(year=date_year, month=date_month, day=date_day, hour=date_hour,
                                                     minute=date_minute, second=date_second, response=str(resp),
                                                     num=satellites_num, ug_id=uid.id)
                else:
                    models.Satellites.objects.create(year=date_year, month=date_month, day=date_day, hour=date_hour,
                                                     minute=date_minute, second=date_second,num=satellites_num, ug_id=uid.id)

                b = '({}, {}, {}, {}, {}, {})'.format(resp['latitude'], resp['longitude'], resp['height'],
                                                      resp['gps_week'], resp['gps_second_of_week'], str(resp['cn0']))
                models.Device_data.objects.create(year=date_year,month=date_month,day=date_day,hour=date_hour,minute=date_minute,second=date_second,data=b,ug_id=uid.id)
                if flag==SRV_CMD_POSITION_RESULT_REQ:
                    latitude=math.modf(float(resp['latitude']))
                    longitude=math.modf(float(resp['longitude']))
                    height=float(resp['height'])
                    payload=pack('<hhfff', int(latitude[1]), int(longitude[1]), latitude[0], longitude[0], height)
                    header = SerialHeader(int(SRV_CMD_POSITION_RESULT_ANS), len(payload))
                    reply = SerialCommand(header, payload)
                    LoraServes_post((reply.bytes).hex(), devicemac, deviceappeui)
            elif flag == CMD_UNIX_REQ:
                utcsec = int(time.time())
                payload = pack('<I',utcsec)
                header = SerialHeader(int(CMD_UNIX_ANS), len(payload))
                reply = SerialCommand(header, payload)
                LoraServes_post((reply.bytes).hex(),devicemac,deviceappeui)
            elif flag == CMD_INIT_REQ:
                public_id = models.Device_list.objects.get(device_mac=devicemac).device_pubilicid
                if not public_id:
                    header = SerialHeader(int(CMD_PUBLIC_ID_REQ),0)
                    reply = SerialCommand(header, None)
                    LoraServes_post((reply.bytes).hex(), devicemac, deviceappeui)
                    return JsonResponse({"code":0,"msg":"success"})
                else:
                    if public_id not in initTime:
                        initTime[public_id] = deviceinittime
                        requesttime=time.time()
                        resp = H.main_entry(
                            bytes.fromhex(public_id), 7, None, 30.47, 114.41, 35
                        )
                        print("请求时间为:",time.time()-requesttime)
                        pd_b64 = resp and resp.get('data')
                        prediction = pd_b64 and b64decode(pd_b64)
                        header = SerialHeader(int(CMD_INIT_ANS), len(prediction))
                        reply = SerialCommand(header, prediction)
                        LoraServes_post((reply.bytes).hex(),devicemac,deviceappeui)
                        print("总时间为:",time.time()-deviceinittime)
                    else:
                        if int(deviceinittime)-int(initTime[public_id])>=10:
                            requesttime=time.time()
                            resp = H.main_entry(
                                bytes.fromhex(public_id), 7, None, 30.47, 114.41, 35
                            )
                            print("请求时间为:",time.time()-requesttime)
                            pd_b64 = resp and resp.get('data')
                            prediction = pd_b64 and b64decode(pd_b64)
                            header = SerialHeader(int(CMD_INIT_ANS), len(prediction))
                            reply = SerialCommand(header, prediction)
                            LoraServes_post((reply.bytes).hex(), devicemac, deviceappeui)
                            print("总时间为:",time.time()-deviceinittime)
                            initTime[public_id] = deviceinittime
                        else:
                            pass
            else:
                pass
        else:
            pass
        return JsonResponse({"code":0,"msg":"success"})
    except Exception:
        return JsonResponse({"code":0,"msg":"success"})


def login(request):
    if request.method=="POST":
        login_form=LoginForm(request.POST)
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            user = models.UserAdmin.objects.filter(username=username, password=password).first()
            if user:
                request.session['permissions'] =user.permissions
                return redirect('/index/')
            else:
                return render(request, 'login.html',{'login_form': login_form,'msg':'用户名或密码错误！'})
        else:
            return render(request, 'login.html', {'login_form': login_form})
    else:
        login_form=LoginForm()
        return render(request, 'login.html', {'login_form': login_form})

def logout(request):
    request.session.flush()
    return redirect('/main/')


def index(request):
    try:
        v=request.session.get('permissions')
        if int(v)>=1:
            device_list=models.Device_list.objects.all()
            return render(request,'index.html',{'device_list':device_list})
        else:
            return HttpResponse("您的权限不够！")
    except Exception:
        return redirect('/login/')

def map(request):
    if request.method=="GET":
        uid = request.GET.get('nid')
        lastDeviceData = models.Device_data.objects.filter(ug_id=uid).last()
        point = eval(lastDeviceData.data)
        latitude = point[0]
        longitude = point[1]
        return render(request, 'map.html', {'latitude': latitude, 'longitude': longitude})
    else:
        uid = request.POST.get('nid')
        lastDeviceData = models.Device_data.objects.filter(ug_id=uid).last()
        point = eval(lastDeviceData.data)
        latitude = point[0]
        longitude = point[1]
        return JsonResponse({'latitude': latitude, 'longitude': longitude})

def getpoint(request):
    if request.method=='POST':
        uid=request.POST.get('nid')
        devicemac=models.Device_list.objects.get(id=uid).device_mac
        header = SerialHeader(int(CMD_POINT_REQ), 0)
        reply = SerialCommand(header, None)
        LoraServes_post((reply.bytes).hex(), devicemac, '0102030405060708')
        return JsonResponse({'message':'ok'})

def lora_trash_get():
    url='http://api.easylinkin.com/api/v1/application/data?mac=478B558000310043&token=jsyfzx123456&cid=383'
    resp=requests.get(url)
    data_Lora=resp.json()['data']
    return data_Lora


def test(request):
    try:
        if request.method=='GET':
            getdata=lora_trash_get()
            if len(getdata)==8:
                ret={'full':getdata[0],'fire':getdata[1],'fall':getdata[2],'bat':getdata[3],'distance':int(getdata[4:])}
                resp=HttpResponse(json.dumps(ret))
                resp["Access-Control-Allow-Origin"] = "*"
                resp["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
                resp["Access-Control-Max-Age"] = "1000"
                resp["Access-Control-Allow-Headers"] = "*"
                return resp
            else:
                pass
        else:
            pass
    except Exception:
        pass


def trash(request):
    return render(request,'trash.html')

trashdeviceinfo={'8CF9572000004C20':{'Devaddr':'00004C20','group':'df702'}}

def deviceDatasChanged(request):
    global trashdeviceinfo
    try:
        if request.method=='POST':
            resp = request.body.decode()
            deveui = json.loads(resp)['mac']
            datafromlora = json.loads(resp)['data']
            headers = {}
            headers['Content-Type'] = 'application/json'
            url = 'http://120.92.89.122/agent/lora/deviceDatasChanged'
            postdata = {"data":datafromlora,"devaddr":trashdeviceinfo[deveui]['Devaddr'] ,
                        "deveui": deveui, "fcnt": "1", "group": trashdeviceinfo[deveui]['group'], "port": 3, "shall_reply": 'true'}
            while True:
                r = requests.post(url, headers=headers, data=json.dumps(postdata), verify=False)
                print('Trying to post to Dingtek Serves...')
                if r.json() == 1 and r.status_code == 200:
                    print('Success!')
                    break
            return JsonResponse({"code": 0, "msg": "success"})
        else:
            return HttpResponse('error!')
    except Exception:
        return JsonResponse({"code":0,"msg":"success"})

MAC=['D896E0FFFF010F67','D896E0FFFF010F68','004A77012404DA6E','004A77012404D742']


import binascii

def big_small_end_convert(data):
    return binascii.hexlify(binascii.unhexlify(data)[::-1])

def temcomp(request):
    try:
        if request.method == 'POST':
            nowtime=time.strftime("%Y%m%d%H%M%S")
            resp = request.body.decode()
            deveui = json.loads(resp)['mac']
            datafromlora = json.loads(resp)['data']
            if deveui in MAC and datafromlora[0:6] =='111111' and len(datafromlora) == 16:
                count = int(big_small_end_convert(datafromlora[8:]), 16)
                tem = int(datafromlora[6:8],16)
                if tem >= 128:
                    tem=tem-256
                models.temComp.objects.create(tem=str(tem),count=count,time=nowtime,device_mac=deveui)
            else:
                pass
        else:
            pass
        return JsonResponse({"code": 0, "msg": "success"})
    except Exception:
        return JsonResponse({"code": 0, "msg": "success"})


dataList={'004A77012400DAE0':{'flag':0,'list':[]},
          '004A77012400CB63':{'flag':0,'list':[]},
          '004A770124010C79':{'flag':0,'list':[]},
          '004A7701240103F1':{'flag':0,'list':[]},
          '004A77012400E87A':{'flag':0,'list':[]},
          '004A77012400F005':{'flag':0,'list':[]}}

from app01.utils.threePhaseMeter import *

def electricLorapost(request):
    global dataList
    try:
        resp = request.body.decode()
        devicemac = json.loads(resp)['mac']
        # deviceappeui = json.loads(resp)['appeui']
        if devicemac in dataList:
            datafromlora = json.loads(resp)['data']
            if datafromlora[0:6]=='fefefe':
                if datafromlora[28:36]=='33323333' and len(dataList[devicemac]['list'])==0 and dataList[devicemac]['flag']==0:
                    dataList[devicemac]['list'].append(datafromlora)
                    dataList[devicemac]['flag'] =1
                elif datafromlora[28:36]=='33323433' and len(dataList[devicemac]['list'])==1 and dataList[devicemac]['flag']==1:
                    dataList[devicemac]['list'].append(datafromlora)
                    dataList[devicemac]['flag'] =2
                elif datafromlora[28:36]=='33323533' and len(dataList[devicemac]['list'])==2 and dataList[devicemac]['flag']==2:
                    dataList[devicemac]['list'].append(datafromlora)
                    dataList[devicemac]['flag'] =3
                elif datafromlora[28:36] == '35459337' and len(dataList[devicemac]['list']) == 3 and dataList[devicemac]['flag']==3:
                    dataList[devicemac]['list'].append(datafromlora)
                    dataList[devicemac]['flag'] =4
                elif datafromlora[28:36] == '34459337' and len(dataList[devicemac]['list']) == 4 and dataList[devicemac]['flag']==4:
                    dataList[devicemac]['list'].append(datafromlora)

                    _List=dataList[devicemac]['list']
                    a=parsing(_List)
                    UTCtime=int(time.time())
                    uid = models.ElectricDeviceList.objects.get(deviceMac=devicemac)
                    models.ElectricDeviceData.objects.create(
                    one1=a['组合有功总电能'],
                    one2 =a['组合有功总电能尖'],
                    one3 =a['组合有功总电能峰'],
                    one4 =a['组合有功总电能平'],
                    one5 =a['组合有功总电能谷'],
                    two1 =a['正向有功总电能'],
                    two2 =a['正向有功总电能尖'],
                    two3 =a['正向有功总电能峰'],
                    two4 =a['正向有功总电能平'],
                    two5 =a['正向有功总电能谷'],
                    three1 =a['反向有功总电能'],
                    three2 =a['反向有功总电能尖'],
                    three3 =a['反向有功总电能峰'],
                    three4 =a['反向有功总电能平'],
                    three5 =a['反向有功总电能谷'],
                    four1 =a['瞬时总有功功率'],
                    four2 =a['瞬时A相有功功率'],
                    four3 =a['瞬时B相有功功率'],
                    four4 =a['瞬时C相有功功率'],
                    four5 =a['总功率因数'],
                    four6 =a['A相功率因数'],
                    four7 =a['B相功率因数'],
                    four8 =a['C相功率因数'],
                    four9 =a['状态字'],
                    five1 =a['A相电压'],
                    five2 =a['B相电压'],
                    five3 =a['C相电压'],
                    five4 =a['A相电流'],
                    five5 =a['B相电流'],
                    five6 =a['C相电流'],
                    time=UTCtime, ug_id=uid.id)
                    dataList[devicemac]['flag'] =0
                    dataList[devicemac]['list']=[]
                else:
                    dataList[devicemac]['flag'] = 0
                    dataList[devicemac]['list'] =[]

            else:
                pass
        else:
            pass
        return JsonResponse({"code": 0, "msg": "success"})
    except exceptions:
        return JsonResponse({"code": 0, "msg": "success"})


def getLineData(request):
    if request.method == 'GET':
       ret={
           "errno":0,
           "data":{
            "optionsA": {
                "xAxis":['周2', '周3', '周4', '周6'],
                "series":
                    {
                        # "name": "直接访问",
                        # "data": [
                        #     {"value": ["1997-10-1 00:00:00",684]},{"value": ["1997-10-2 01:00:00",684]},{"value": ["1997-10-2 02:00:00",684]},
                        #     {"value": ["1997-10-4 12:00:00",684]},{"value": ["1997-10-5 16:00:00",684]},{"value": ["1997-10-6 02:00:00",684]},
                        #     {"value": ["1997-10-7 01:00:00",684]},{"value": ["1997-10-8 22:00:00",684]},
                        #     {"value": ["1997-10-9 22:00:00",684]},{"value": ["1997-10-10 22:00:00",684]},{"value": ["1997-10-11 22:00:00",684]},
                        #         ]
                        # "data":[[1573004486000,150],[1573004734000,150],[1573004799000,200],[1573004899000,350],[1573005900000,200]]
                        "data":['123','456','123','456']
                    }
                    # {
                    #     "name": "邮件营销",
                    #     "data": [120, 132, 101, 134, 90, 230, 210]
                    # },
                    # {
                    #     "name": "联盟广告",
                    #     "data": [220, 182, 191, 234, 290, 330, 310]
                    # },
                    # {
                    #     "name": "视频广告",
                    #     "data": [150, 212, 201, 154, 190, 330, 410]
                    # },
                    # {
                    #     "name": "搜索引擎",
                    #     "data": [820, 832, 901, 934, 1290, 1330, 1320]
                    # }
                }}}
       return JsonResponse(ret)


def filter(request):
    a=models.Satellites.objects.filter(year=2019,day=19,hour=18)
    for i in a:
        print(i.response)
    return HttpResponse(1)


def singlepower(request):
    global dataList
    try:
        if request.method=="GET":
            retdata = []
            selectdate=request.GET.get('date')
            utcdatetime = int(time.mktime(time.strptime(selectdate, "%Y%m%d")))
            uid=request.GET.get('nid')
            singlepowerdata=models.ElectricDeviceData.objects.filter(ug_id=uid,time__gte=utcdatetime,time__lte=utcdatetime+86400)
            for i in singlepowerdata:
                retdata.append([i.time*1000,round(i.four1*100,2)])
            rsp={
            "errno": 0,
            "data": {
                "optionsA": {
                    "series":
                        {
                            "data":retdata
                        }
                }}}
            return JsonResponse(rsp)
    except exceptions:
        rsp={
            "errno": 0,
            "data": {
                "optionsA": {
                    "series":
                        {
                            "data":0
                        }
                }}}
        return JsonResponse(rsp)


# def singlepower(request):
#     if request.method=="GET":
#         retdata=[]
#         uid = request.GET.get('nid')
#         datetime = time.strftime("%Y%m%d", time.localtime(time.time())) + '0000'
#         utcdatetime=int(time.mktime(time.strptime(datetime, "%Y%m%d%H%M%S")))
#         singlepowerdata = models.ElectricDeviceData.objects.filter(ug_id=uid,time__gte=utcdatetime)
#         for i in singlepowerdata:
#             retdata.append([i.time*1000,i.four1*100])
#         rsp={
#             "errno": 0,
#             "data": {
#                 "optionsA": {
#                     "series":
#                         {
#                             "data":retdata
#                         }
#                 }}}
#
#         return JsonResponse(rsp)



def writedaliycons(request):
    try:
        if request.method=="GET":
            for i in dataList:
                uid=models.ElectricDeviceList.objects.get(deviceMac=i)
                last=models.ElectricDeviceData.objects.filter(ug_id=uid.id).last()
                first=models.ElectricDeviceData.objects.filter(ug_id=uid.id,time__gte=last.time-86400).first()
                if uid and last:
                # models.DailyElectcons.objects.create(econs=last.one1-first.one1,ug_id=uid.id,date=time.strftime("%Y%m%d",time.localtime(first.time)))
                    models.DailyElectcons.objects.update_or_create(defaults={'econs':round(last.one1-first.one1,4)},ug_id=uid.id,date=time.strftime("%Y/%m/%d",time.localtime(first.time)))
                else:
                    models.DailyElectcons.objects.update_or_create(defaults={'econs': 0},
                                                                   ug_id=uid.id, date=time.strftime('%Y/%m/%d',time.localtime(time.time()-86400)))
        return JsonResponse({"code": 0, "msg": "success"})
    except exceptions:
        return JsonResponse({"code": 1, "msg": "fail"})




def totalenegrydata(request):
    global dataList
    if request.method=="GET":
        _dataList=[]
        timeList=[]
        for i in dataList:
            singledatalist=[]
            singletimelist=[]
            uid=models.ElectricDeviceList.objects.get(deviceMac=i)
            count=models.DailyElectcons.objects.filter(ug_id=uid).count()
            if count<14:
                initdata=models.DailyElectcons.objects.filter(ug_id=uid)
                for i in initdata:
                    singledatalist.append(i.econs*100)
                    singletimelist.append(i.date)
            else:
                initdata=models.DailyElectcons.objects.filter(ug_id=uid).order_by('-id')[:14]
                for i in initdata:
                    singledatalist.append(i.econs*100)
                    singletimelist.append(i.date)
                singledatalist.reverse()
                singletimelist.reverse()
            _dataList.append(singledatalist)
            timeList.append(singletimelist)
        count=len(_dataList[0])
        totaldata=[]
        for i in range(0,count):
            sum=0
            for j in _dataList:
                sum=sum+j[i]
            totaldata.append(int(sum* 0.6907))
        rsp = {
            "errno": 0,
            "data": {
                "optionsA": {
                    "xAxis": timeList[0],
                    "series":
                        {
                            "data": totaldata
                        }
                }}}
        return JsonResponse(rsp)



# def sinenegrydata(request):
#     if request.method == "GET":
#         uid = request.GET.get('nid')



def sinenegrydata(request):
    if request.method=="GET":
        retdatalist=[]
        rettimelist=[]
        uid = request.GET.get('nid')
        count=models.DailyElectcons.objects.filter(ug_id=uid).count()
        if count<14:
            initdata=models.DailyElectcons.objects.filter(ug_id=uid)
            for i in initdata:
                retdatalist.append(int(i.econs*100))
                rettimelist.append(i.date)
        else:
            initdata=models.DailyElectcons.objects.filter(ug_id=uid).order_by('-id')[:14]
            for i in initdata:
                retdatalist.append(int(i.econs*100* 0.6907))
                rettimelist.append(i.date)
            retdatalist.reverse()
            rettimelist.reverse()
        rsp={
            "errno": 0,
            "data": {
                "optionsA": {
                    "xAxis":rettimelist,
                    "series":
                        {
                            "data":retdatalist
                        }
                }}}
        return JsonResponse(rsp)



def totalpower(request):
    global dataList
    if request.method=="GET":
        uid=[]
        totaldata=[]
        retdata = []
        selectdate=request.GET.get('date')
        utcdatetime = int(time.mktime(time.strptime(selectdate, "%Y%m%d")))
        if selectdate==time.strftime("%Y%m%d"):
            for i in dataList:
                id = models.ElectricDeviceList.objects.get(deviceMac=i)
                uid.append(id)
            datetime = time.strftime("%Y%m%d", time.localtime(time.time())) + '0000'
            utcdatetime = int(time.mktime(time.strptime(datetime, "%Y%m%d%H%M%S")))
            singlepowerdata = models.ElectricDeviceData.objects.filter(ug_id=uid[0], time__gte=utcdatetime)
            totaldata.append(singlepowerdata)
            count = singlepowerdata.count()
            for i in uid[1:]:
                a = models.ElectricDeviceData.objects.filter(ug_id=i).order_by('-id')[:count]
                if a.count()==count:
                    s = []
                    for i in a:
                        s.append(i)
                    s.reverse()
                    totaldata.append(s)
        else:
            for i in dataList:
                id = models.ElectricDeviceList.objects.get(deviceMac=i)
                uid.append(id)
            singlepowerdata = models.ElectricDeviceData.objects.filter(ug_id=uid[0], time__gte=utcdatetime,time__lte=utcdatetime+86400)
            totaldata.append(singlepowerdata)
            count = singlepowerdata.count()
            for i in uid[1:]:
                # s = models.ElectricDeviceData.objects.filter(ug_id=i,time__gte=utcdatetime).first()
                s = models.ElectricDeviceData.objects.filter(ug_id=i, time__gte=utcdatetime)[:count]
                if s.count()==count:
                    totaldata.append(s)
        totalpower = []
        for i in range(count):
            power = 0
            for j in totaldata:
                power += j[i].four1
            totalpower.append(power)
        timelist = []
        for i in totaldata[0]:
            timelist.append(i.time)
        for i in range(count):
            retdata.append([timelist[i] * 1000, round(totalpower[i] * 100,2)])
        rsp = {
            "errno": 0,
            "data": {
                "optionsA": {
                    "series":
                        {
                            "data": retdata
                        }
                }}}

        return JsonResponse(rsp)




# def aotalpower(request):
#     global dataList
#     if request.method=="GET":
#         retdata=[]
#         totaldata=[]
#         uid=[]
#         for i in dataList:
#             id=models.ElectricDeviceList.objects.get(deviceMac=i)
#             uid.append(id)
#         datetime = time.strftime("%Y%m%d", time.localtime(time.time())) + '0000'
#         utcdatetime=int(time.mktime(time.strptime(datetime, "%Y%m%d%H%M%S")))
#         singlepowerdata = models.ElectricDeviceData.objects.filter(ug_id=uid[0],time__gte=utcdatetime)
#         totaldata.append(singlepowerdata)
#         count=singlepowerdata.count()
#         for i in uid[1:]:
#             t = models.ElectricDeviceData.objects.filter(ug_id=i).count()
#             # s = models.ElectricDeviceData.objects.filter(ug_id=i)[t-count:]
#             a=models.ElectricDeviceData.objects.filter(ug_id=i).order_by('-id')[:count]
#             s=[]
#             for i in a:
#                 s.append(i)
#             s.reverse()
#             totaldata.append(s)
#         totalpower=[]
#         for i in range(count):
#             power=0
#             for j in totaldata:
#                 power+=j[i].four1
#             totalpower.append(power)
#         timelist=[]
#         for i in totaldata[0]:
#             timelist.append(i.time)
#         for i in range(count):
#             retdata.append([timelist[i]*1000,totalpower[i]*100])
#         rsp={
#             "errno": 0,
#             "data": {
#                 "optionsA": {
#                     "series":
#                         {
#                             "data":retdata
#                         }
#                 }}}
#
#         return JsonResponse(rsp)

def datalistdata(request):
    if request.method=='GET':
        power=[]
        energy=[]
        utcdatetime = int(time.mktime(time.strptime(time.strftime("%Y%m%d", time.localtime(time.time())), "%Y%m%d")))
        uid=[]
        for i in dataList:
            id = models.ElectricDeviceList.objects.get(deviceMac=i)
            uid.append(id)
        for i in uid:
            last = models.ElectricDeviceData.objects.filter(ug_id=i).last()
            first=models.ElectricDeviceData.objects.filter(ug_id=i,time__lte=utcdatetime).last()
            power.append(round(last.four1*100,2))
            energy.append(int((last.one1-first.one1)*100))
        return JsonResponse(
            {
                "power":power,
                "energy":energy
            }
        )

from app01.utils.get12Month import *


month=['01','02','03','04','05','06','07','08','09','10','11','12']
def singleyeardata(request):
    if request.method=='GET':
        uid = request.GET.get('nid')
        rettimelist=[]
        retdatalist=[]
        last = models.ElectricDeviceData.objects.filter(ug_id=uid).last()
        lasttime=time.strftime("%Y%m", time.localtime(last.time))
        yearDate=get12Month(lasttime)
        for i in yearDate:
            utcFirst=int(time.mktime(time.strptime(i[0], "%Y%m")))
            utcLast = int(time.mktime(time.strptime(i[1], "%Y%m")))
            dataFirst = models.ElectricDeviceData.objects.filter(ug_id=uid,time__gte=utcFirst,time__lte=utcLast).first()
            dataLast = models.ElectricDeviceData.objects.filter(ug_id=uid,time__gte=utcFirst,time__lte=utcLast).last()
            if dataFirst and dataLast:
                data=round(dataLast.one1-dataFirst.one1,4)
                retdatalist.append(int(data * 100))
                rettimelist.append(i[0])
        rsp={
            "errno": 0,
            "data": {
                "optionsA": {
                    "xAxis":rettimelist,
                    "series":
                        {
                            "data":retdatalist
                        }
                }}}
        return JsonResponse(rsp)

def totalyeardata(request):
    if request.method=='GET':
        rettimelist = []
        retdatalist = []
        last = models.ElectricDeviceData.objects.all().last()
        lasttime = time.strftime("%Y%m", time.localtime(last.time))
        yearDate = get12Month(lasttime)
        for i in yearDate:
            utcFirst = int(time.mktime(time.strptime(i[0], "%Y%m")))
            utcLast = int(time.mktime(time.strptime(i[1], "%Y%m")))
            sum=0
            for j in dataList:
                uid = models.ElectricDeviceList.objects.get(deviceMac=j)
                datafirst = models.ElectricDeviceData.objects.filter(ug_id=uid.id, time__gte=utcFirst,time__lte=utcLast).first()
                datalast = models.ElectricDeviceData.objects.filter(ug_id=uid.id,time__gte=utcFirst, time__lte=utcLast).last()
                if datafirst and datalast:
                    data = datalast.one1 - datafirst.one1
                else:
                    data=0
                sum=sum+data
            if sum!=0:
                retdatalist.append(round(sum * 100,2))
                rettimelist.append(i[0])
        rsp={
            "errno": 0,
            "data": {
                "optionsA": {
                    "xAxis":rettimelist,
                    "series":
                        {
                            "data":retdatalist
                        }
                }}}
        return JsonResponse(rsp)

def getmonthenergy(request):
    if request.method=='GET':
        monthfirst=time.strftime("%Y%m")
        i= month.index(monthfirst[4:6])
        if monthfirst[4:6] == '12':
            monthlast = int(time.mktime(time.strptime(str(int(monthfirst[0:4]) + 1), "%Y")))
        else:
            monthlast = int(time.mktime(time.strptime((monthfirst[0:4] + month[i + 1]), "%Y%m")))
        sum = 0
        for j in dataList:
            uid = models.ElectricDeviceList.objects.get(deviceMac=j)
            datafirst = models.ElectricDeviceData.objects.filter(ug_id=uid.id, time__gte=monthfirst).first()
            datalast = models.ElectricDeviceData.objects.filter(ug_id=uid.id, time__lte=monthlast).last()
            data = datalast.one1 - datafirst.one1
            sum = sum + data
        rsp={"data":int(sum * 100*0.6907)}
        return JsonResponse(rsp)